package com.changgou.pay.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.pay.config.RabbitMQConfig;
import com.changgou.pay.service.WXPayService;
import com.changgou.util.ConvertUtils;
import com.github.wxpay.sdk.WXPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author kfzhao
 * @version 1.0
 * @className WXPayController
 * @description
 * @date 2022/1/4 18:07
 */
@RequestMapping("/wxpay")
@RestController
@Slf4j
public class WXPayController {
    @Autowired
    private WXPayService wxPayService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/nativePay")
    public Result nativePay(@RequestParam("orderId") String orderId, @RequestParam("money") Integer money) {
        Map resultMap = wxPayService.nativePay(orderId, money);
        return new Result(true, StatusCode.OK, "", resultMap);
    }

    @RequestMapping("/notify")
    public void notifyLogic(HttpServletRequest request, HttpServletResponse response) {
        log.info("支付成功回调");
        try {
            // 1.输入流转换为字符串
            String xml = ConvertUtils.convertToString(request.getInputStream());
            log.info(xml);
            // 基于微信发送的通知内容，完成后续的业务逻辑
            Map<String, String> map = WXPayUtil.xmlToMap(xml);
            if ("SUCCESS".equals(map.get("result_code"))) {
                // 查询订单
                Map result = wxPayService.queryOrder(map.get("out_trade_no"));
                log.info("查询订单结果:" + result);
                if ("SUCCESS".equals(map.get("result_code"))) {
                    // 将订单消息发送到mq
                    Map message = new HashMap();
                    message.put("orderId", result.get("out_trade_no"));
                    message.put("transactionId", result.get("transaction_id"));
                    // 消息发送 完成订单信息的修改
                    rabbitTemplate.convertAndSend("", RabbitMQConfig.ORDER_PAY, JSON.toJSONString(message));

                    // 完成websocket双向通信 完成订单页面的跳转
                    rabbitTemplate.convertAndSend("paynotify", "", result.get("out_trade_no"));
                } else {
                    // 输出错误原因
                    log.error(map.get("err_code_des"));
                }
            } else {
                // 输出错误原因
                log.error(map.get("err_code_des"));
            }

            // 2.商家需要向微信提供结果通知
            response.setContentType("text/xml");
            String data = "<xml><return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[OK]]></return_msg></xml>";
            response.getWriter().write(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //log.info("支付成功回调");
    }

    /**
     * 基于微信查询订单
     *
     * @param orderId
     * @return
     * @throws
     * @description
     * @author kfzhao
     * @date 2022/1/5 0:17
     */
    @GetMapping("/query/{orderId}")
    public Result queryOrder(@PathVariable("orderId") String orderId) {
        Map map = wxPayService.queryOrder(orderId);
        return new Result(true, StatusCode.OK, "查询订单成功", map);
    }

    /**
     * 基于微信关闭订单
     *
     * @param orderId
     * @return com.changgou.entity.Result
     * @throws
     * @description
     * @author kfzhao
     * @date 2022/1/5 0:22
     */
    @PutMapping("/close/{orderId}")
    public Result closeOrder(@PathVariable("orderId") String orderId) {
        Map map = wxPayService.closeOrder(orderId);
        return new Result(true, StatusCode.OK, "关闭订单成功", map);
    }

}
